<template>
  <!-- 场景管理页面 -->
  <div>
    <el-row class="ruleScene container">
      <el-col style="margin-right:10px;" class="content-left">
        <!-- 操作区域 -->
        <upper-template
          @search="searchForm.page=1,searchFunc()"
          @clear="
            (searchForm.sceneName = ''), (searchForm.sceneCode = '')
          "
        >
          <!-- 操作按钮区 -->
          <template slot="buttonArea">
            <el-button @click="addOrEditFunc('1')">新增</el-button>
            <el-button @click="addOrEditFunc('2')">编辑</el-button>
            <el-button @click="delFunc()">删除</el-button>
            <el-button @click="addOrEditFunc('3')">查看</el-button>
            <el-button @click="addOrEditFunc('5')">复制</el-button>
            <el-button @click="changeStatus('1')">生效</el-button>
            <el-button @click="changeStatus('0')">失效</el-button>
            <el-button @click="sceneRun">运行</el-button>
            <el-button @click="runResult">运行结果</el-button>
            <el-button @click="toScenecontrast">场景对比</el-button>
          </template>
          <!-- 搜索区 -->
          <template slot="searchArea">
            <el-form
              :model="searchForm"
              ref="searchForm"
              label-width="87px"
              label-position="left"
              size="mini"
            >
              <el-form-item label="场景名称：">
                <el-input
                  v-model="searchForm.sceneName"
                  style="width:150px"
                ></el-input>
              </el-form-item>
              <el-form-item label="场景编码：">
                <el-input
                  v-model="searchForm.sceneCode"
                  style="width:150px"
                ></el-input>
              </el-form-item>
            </el-form>
          </template>
          <!-- 显示隐藏区 -->
          <template slot="columnHide">
            <el-checkbox-group v-model="checkList">
              <el-checkbox
                v-for="item in textData"
                :label="item.label"
                :key="item.prop"
                >{{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </template>
        </upper-template>

        <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          @row-click="authorizeFor"
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            prop="sceneCode"
            label="场景编码"
            :show-overflow-tooltip="true"
            v-if="columnState[0]"
          >
          </el-table-column>
          <el-table-column
            prop="sceneName"
            label="场景名称 "
            :show-overflow-tooltip="true"
            v-if="columnState[1]"
          >
          </el-table-column>

          <el-table-column
            prop="status"
            label="状态 "
            :show-overflow-tooltip="true"
            v-if="columnState[2]"
            :formatter="row => (row.status == 1 ? '生效' : '未生效')"
          >
          </el-table-column>

          <el-table-column
            prop="runType"
            label="清空历史记录 "
            :show-overflow-tooltip="true"
            v-if="columnState[3]"
            :formatter="row => (row.runType == 1 ? '是' : '否')"
          >
          </el-table-column>
           <!-- <el-table-column
            prop="sceneType"
            label="明细方式 "
            :show-overflow-tooltip="true"
            v-if="columnState[4]"
            :formatter="formatSceneType"
          >
          </el-table-column> -->
          <el-table-column
            prop="runStatus"
            label="运行状态 "
            :show-overflow-tooltip="true"
            v-if="columnState[4]"
            :formatter="formatRunStatus"
          >
          </el-table-column>
          <el-table-column
            prop="creator"
            :show-overflow-tooltip="true"
            label="创建人"
            sortable
            v-if="columnState[5]"
          >
          </el-table-column>
          <el-table-column
            prop="createdTm"
            :show-overflow-tooltip="true"
            label="创建时间"
            sortable
            v-if="columnState[6]"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.createdTm">
                {{ timeFormat(scope.row.createdTm) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="modifier"
            :show-overflow-tooltip="true"
            label="修改人"
            sortable
            v-if="columnState[7]"
            :formatter="row => row.modifier || '-'"
          >
          </el-table-column>
          <el-table-column
            prop="modifiedTm"
            :show-overflow-tooltip="true"
            label="修改时间"
            sortable
            v-if="columnState[8]"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.modifiedTm">
                {{ timeFormat(scope.row.modifiedTm) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          @refresh="searchFunc"
          :total="total"
        ></pagination>
      </el-col>
    </el-row>
    <!-- 场景对比 -->
    <el-dialog
      v-dialogDrag
      title="场景对比"
      :visible.sync="scenecontrastDi"
      width="60%"
      top="2%"
    >
      <sceneContrast ref="scenecontrast" :sceneCodeList="sceneCodeList"/>
         <div slot="footer">
        <el-button @click="scenecontrastDi = false">关闭</el-button>
      </div>

    </el-dialog>
    <!-- 运行结果 -->
    <el-dialog
      v-dialogDrag
      title="运行结果"
      :visible.sync="runResultDataDi"
      width="60%"
      top="2%"
    >
      <sceneResult :sceneCode="sceneCode"/>
    </el-dialog>
    <el-dialog v-dialogDrag :title="titleName" :visible.sync="addOrEdit" width="85%" top="2%" @close="addOrEditAfterClose">
      <el-tabs v-model="activeName" @tab-click="handleClick" :before-leave="beforeHandle">
        <el-tab-pane label="基本信息" name="sceneBasic">
          <el-form
            :model="saveForm"
            ref="saveOrEditRef"
            label-width="110px"
            label-position="left"
            :rules="saveFormRules"
          >
            <el-form-item label="通用设置项"></el-form-item>
            <el-row>
              <el-col :span="8" :offset="2">
                <el-form-item label="场景编码：" prop="sceneCode">
                  <el-input
                    v-model="saveForm.sceneCode"
                    maxlength="32"
                    :disabled="operateType==2||operateType==3"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="2">
                <el-form-item label="场景名称：" prop="sceneName">
                  <el-input
                    v-model="saveForm.sceneName"
                    maxlength="200"
                    :disabled="operateType==3"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="18" :offset="2">
                <el-form-item label="描述：" prop="descn">
                  <el-input
                    v-model="saveForm.descn"
                    type="textarea"
                    maxlength="200"
                    :disabled="operateType==3"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="账户级设置项"></el-form-item>
            <el-row>
              <el-col :span="18" :offset="2">
                <el-form-item label="是否清空结果：" prop="runType">
                  <el-radio v-model="saveForm.runType" label="0">否</el-radio>
                  <el-radio v-model="saveForm.runType" label="1">是</el-radio>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button v-if="operateType!=3" @click="saveFunc">确 定</el-button>
            <el-button @click="addOrEdit = false">取 消</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="规则配置" name="sceneRules">
          <el-row>
            <sceneNode :sceneCode="sceneCode" :operateType="operateType"/>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="图形展示" name="sceneShow">
          <sceneImg ref="sceneImg" :sceneCode="sceneCode" :sceneName="sceneName"/>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" v-if="activeName=='sceneBasic'">
        <el-button v-if="operateType!=3" @click="saveFunc">确 定</el-button>
        <el-button @click="addOrEdit = false">取 消</el-button>
      </div>
      <div slot="footer" v-if="activeName!='sceneBasic'"></div>
    </el-dialog>
  </div>
</template>

<script>
import { ruleScene } from "@/api/index";
import upperTemplate from "@/components/upperTemplate.vue"
import onlyOneSearch from "@/components/onlyOneSearch";
import sceneResult from "./components/sceneResult";
import sceneImg from "./components/sceneImg";
import sceneNode from "./components/sceneNode";
import sceneContrast from "./components/sceneContrast";
import moment from "moment";
export default {
  data() {
    return {
      sceneCodeList: [], // 传输的值
      // 场景对比弹出框标识
      scenecontrastDi: false,
      //运行结果弹出框标识
      runResultDataDi: false,
      // 列隐藏依据数据
      textData: [
        { prop: "sceneCode", label: "场景编码", disabled: true },
        { prop: "sceneName", label: "场景名称", disabled: true },
        { prop: "status", label: "状态", disabled: true },
        { prop: "runType", label: "清空历史记录", disabled: true },
        //{ prop: "sceneType", label: "明细方式", disabled: true },
        { prop: "runStatus", label: "运行状态", disabled: true },
        { prop: "creator", label: "创建人", disabled: true },
        { prop: "createdTm", label: "创建时间", disabled: true },
        { prop: "modifier", label: "修改人", disabled: true },
        { prop: "modifiedTm", label: "修改时间", disabled: true }
      ],
      // 显示的列
      checkList: [],
      //查询时默认条件
      searchForm: {
        page: 1,
        size: 15,
        sceneCode: "",
        sceneName: ""
      },
      total: 0,
      tableData: [],
      //场景编号-参数
      sceneCode: "",
      sceneName: "",
      //操作标识
      operateType: "1",
      //保存实体
      saveForm: {runType:"0"},
      //表单字段规则校验
      saveFormRules: {
        sceneCode: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_-]{1,30}$/,
            message: "必须是英文或者数字且长度不能超过30",
            trigger: "blur"
          }
        ],
        sceneName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z0-9（）()\[\]【】{}]{1,60}$/,
            message: "必须是1-15位的汉字、字母、数字或括号",
            trigger: "blur"
          }
        ]
      },
      //新增编辑弹出框标识
      addOrEdit: false,
      //新增编辑弹出框名称
      titleName: "",
      activeName: "sceneBasic",
      configRow: []
    };
  },
  components: {
    onlyOneSearch,
    sceneResult,
    sceneNode,
    sceneContrast,
    sceneImg
  },
  created() {
    this.checkListInit();
  },
  computed: {
    columnState() {
      let arr = [],
        arr1 = this.textData,
        arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    }
  },
  mounted() {
    this.searchFunc();
  },
  watch: {},
  methods: {
    checkListInit() {
      this.checkList = this.textData.map(v => {
        return v.label;
      });
    },
    searchFunc() {
      let data = this.searchForm;
      ruleScene.queryScenePage(data).then(res => {
        if (res.code === 200) {
          this.tableData = res.datas.rows;
          this.total = res.datas.total;
        }
      });
    },
    //新增，修改，查看，复制
    addOrEditFunc(val) {
      //修改操作标识
      this.operateType = val;
      if(this.$refs.saveOrEditRef) {
        this.$refs.saveOrEditRef.resetFields();
      }
      if (val === '1') {
        this.titleName = "新增场景";
        this.sceneCode = '';
        this.saveForm = {runType:"0"};
      } else if (val === '2') {
        this.titleName = "编辑场景";
      } else if (val === '3') {
        this.titleName = "查看场景";
      } else if (val === '5') {
        this.titleName = "复制场景";
      }
      if (val != '1') {
        let selection = this.$refs.multipleTable.selection;
        if (selection.length < 1) {
          return this.$message.warning("请选择一条数据");
        } else if (selection.length > 1) {
          return this.$message.warning("只能选择一条数据");
        } else {
          if (selection[0].status == "1"&&val=="2") {
            return this.$message.warning("已经生效的场景，不能编辑");
          } else {
            this.configRow = selection;
            this.sceneCode = selection[0].sceneCode;
          }
        }
      }
      
      let formData = {sceneCode:this.sceneCode};
      ruleScene.querySceneByCode(formData).then(res => {
        if (val != "1") {
          this.saveForm = res.data;
          if (val == "5") {
            this.saveForm.sceneCode = '';
          }
        }
      });
      this.addOrEdit = false;
      this.activeName = "sceneBasic";
      this.addOrEdit = true;
    },
    //保存
    saveFunc() {
      this.$refs["saveOrEditRef"].validate(valid => {
        if (valid) {
          let data = {
            operateType: this.operateType,
            status: "0",
            ...this.saveForm
          };
          let checkData = {
            sceneCode:data.sceneCode
          };
          if(this.operateType == '5') {
            data.sceneCodeOld = this.sceneCode;
            ruleScene.checkCode(checkData).then(res => {
              if (res.code == 200&&res.message != null && res.message != '') {
                this.$message.warning("场景编码已存在");
              } else {
                ruleScene.saveCopy(data).then(res => {
                  if (res.code == 200) {
                    this.$message.success("保存成功");
                    //this.addOrEdit = false;
                    this.sceneCode = data.sceneCode
                    this.sceneName = data.sceneName
                    this.searchFunc();
                  } else {
                    this.$message.error(res.message || "保存失败");
                  }
                });
              }
            });
            
          } else if(this.operateType == '1'){
            ruleScene.checkCode(checkData).then(res => {
              if (res.code == 200&&res.message != null && res.message != '') {
                this.$message.warning("场景编码已存在");
              } else {
                ruleScene.saveScene(data).then(res => {
                  if (res.code == 200) {
                    this.$message.success("保存成功");
                    this.sceneCode = data.sceneCode
                    this.sceneName = data.sceneName
                    //this.addOrEdit = false;
                    this.searchFunc();
                  } else {
                    this.$message.error(res.message || "保存失败");
                  }
                });
              }
            });
            
          } else {
            ruleScene.saveScene(data).then(res => {
              if (res.code == 200) {
                this.$message.success("保存成功");
                //this.addOrEdit = false;
                this.searchFunc();
              } else {
                this.$message.error(res.message || "保存失败");
              }
            });
          }
        }
      });
    },
    //删除场景
    delFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      for(let i = 0;i < selection.length;i++) {
        if(selection[i].status == "1") {
          return this.$message.warning("存在已生效场景，不能删除");
        }
      }
      this.$confirm("您确定要删除选中场景吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = { ids: selection.map(v => v.sceneCode) };
          ruleScene.deleteScene(data).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    formatSceneType(row,column) {
        if (row.sceneType==1) {
          return "直接生成到源表";
        } else if (row.sceneType==2) {
          return "生成到新表：行模式";
        } else if (row.sceneType==3) {
          return "生成到新表：列模式";
        } else {
          return "";
        }
    },
    formatRunStatus(row,column) {
        if (row.runStatus==0) {
          return "场景未运行";
        }else if (row.runStatus==1) {
          return "场景正在运行中";
        } else if (row.runStatus==2) {
          return "场景运行结束";
        } else if (row.runStatus==3) {
          return "场景运行停止";
        } else if (row.runStatus==4) {
          return "场景正在预处理";
        } else if (row.runStatus==5) {
          return "";
        } else if (row.runStatus==6) {
          return "场景运行出错";
        } else {
          return "";
        }
    },
    // 场景对比
    toScenecontrast(){
     let checked = this.$refs.multipleTable.selection;
       if (checked.length != 2) {
        return this.$message.warning("请选择两条数据");
      }  else {
        this.sceneCodeList = checked;
        this.scenecontrastDi = true;
         setTimeout((res)=>{
           this.$refs.scenecontrast.init()
         },10)
      }
    },
    //运行结果
    runResult () {
      let checked = this.$refs.multipleTable.selection;
      if (checked.length < 1) {
        return this.$message.warning("请选择一条数据");
      } else if (checked.length > 1) {
        return this.$message.warning("只能选择一条数据");
      } else {
        this.configRow = checked[0];
        this.sceneCode=this.configRow.sceneCode;
        this.runResultDataDi = true;
      }
    },
    //生效，失效
    changeStatus(valFlag) {
      let val = valFlag == "1" ? "生效" : "失效";
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择一条数据");
      } else if (selection.length > 1) {
        return this.$message.warning("只能选择一条数据");
      } else if (selection[0].status == "1"&&valFlag=="1") {
        return this.$message.warning("场景已生效");
      } else if (selection[0].status != "1"&&valFlag!="1") {
        return this.$message.warning("场景未生效");
      } else {
        this.configRow = selection[0];
        this.sceneCode = this.configRow.sceneCode;
        if (selection.length < 1) {
          return this.$message.warning("请选择要" + val + "的场景");
        }
        this.$confirm(`您确定要${val}所选场景吗?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            let data = {
              sceneCode: this.sceneCode
            };
            if (valFlag == "1") {
              ruleScene.activityScene(data).then(res => {
                if (res.code == 200) {
                  this.$message.success(val + "成功");
                  this.searchFunc();
                } else {
                  this.$message.error(res.message);
                }
              });
            } else {
              ruleScene.inActivityScene(data).then(res => {
                if (res.code == 200) {
                  this.$message.success(val + "成功");
                  this.searchFunc();
                } else {
                  this.$message.error(res.message);
                }
              });
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消" + val
            });
          });
      }
    },
    addOrEditAfterClose() {
      this.addOrEdit = false;
      this.activeName="sceneBasic"
    },
    beforeHandle() {
      if (this.sceneCode.length == 0) {
        this.$message.error("请先保存场景信息");
        return false;
      }
    },
    handleClick(tab,event) {
      if(this.activeName == "sceneShow"){
        setTimeout(()=>{
        this.$refs.sceneImg.init()
        },10)
      }
      
    },
    //场景运行
    sceneRun () {
      let checked = this.$refs.multipleTable.selection;
      if (checked.length < 1) {
        return this.$message.warning("请选择一条数据");
      } else if (checked.length > 1) {
        return this.$message.warning("只能选择一条数据");
      } else {
        if  (checked[0].status == "1") {
          this.$confirm(`您确定要运行所选场景吗?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
              let data = {
                sceneCode: checked[0].sceneCode
              };
              ruleScene.sceneRun(data).then(res=>{
                if(res.code == 200) {
                  this.$message.success("场景任务发送成功");
                  this.searchFunc();
                } else {
                  this.$message.error(res.message);
                }
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消" + val
              });
            });
        } else {
          return this.$message.warning("场景未生效，不能运行");
        }
        
      }
    },
    //   点击行选中
    authorizeFor(row) {
        if (this.$refs.multipleTable) {
            this.$refs.multipleTable.clearSelection()
        }
        this.$refs.multipleTable.toggleRowSelection(row, true)
    },
    timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD HH:mm:ss");
      else return "";
    },
    handleSizeChange(val) {
      this.searchForm.size = val;
      console.log(val, "每页数");
      this.searchFunc();
    },
    handleCurrentChange(val) {
      this.searchForm.page = val;
      console.log(val, "当前页");
      this.searchFunc();
    }
  }
};
</script>

<style lang="scss" scoped>
.dialogSearchBox {
  header {
    text-align: center;
    span {
      margin: 0 20px;
    }
  }
}
.el-transfer__buttons{
  width: 150px;
}
.el-transfer__button{
  margin-left:0px;
}
</style>